package com.hts.utils.word;

import org.apache.poi.xwpf.usermodel.BodyElementType;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFSDT;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author hs
 * @version 1.0
 * @date: 2023/5/30
 */
public class MyXWPDocument extends XWPFDocument {
    public MyXWPDocument(InputStream inputStream) throws IOException {
        super(inputStream);
    }
    public boolean removeBodyElementAndSTD(int pos) {
        if (pos >= 0 && pos < bodyElements.size()) {
            BodyElementType type = bodyElements.get(pos).getElementType();
            if (type == BodyElementType.TABLE) {
                int tablePos = getTablePos(pos);
                tables.remove(tablePos);
                getDocument().getBody().removeTbl(tablePos);
            }
            if (type == BodyElementType.PARAGRAPH) {
                int paraPos = getParagraphPos(pos);
                paragraphs.remove(paraPos);
                getDocument().getBody().removeP(paraPos);
            }
            if(type == BodyElementType.CONTENTCONTROL){
                int i=-1;
                int j =0;
               if(!contentControls.isEmpty()){
                   for (XWPFSDT contentControl : contentControls) {
                       if (contentControl == bodyElements.get(pos)) {
                           i = j;
                           break;
                       }
                       j++;
                   }
                   if(i!=-1){
                       getDocument().getBody().removeSdt(i);
                       contentControls.remove(i);
                   }
               }
            }
            bodyElements.remove(pos);
            return true;
        }
        return false;
    }
}
